<?php

	// +----------------------------------------------------------------------
	// | 商品模型
	// +----------------------------------------------------------------------
	// | Copyright (c) 2015-2024 http://www.yicmf.com, All rights reserved.
	// +----------------------------------------------------------------------
	// | Author: 微尘 <yicmf@qq.com>
	// +----------------------------------------------------------------------

	namespace app\event\store;

	use app\common\event\Base;
	use app\model\store\Activity as ActivityModel;
	use app\model\store\GoodAttribute as GoodAttributeModel;
	use app\model\store\GoodAttributeValue as GoodAttributeValueModel;
	use app\model\store\GoodEvaluate as GoodEvaluateModel;
	use app\model\store\GoodCollection as GoodCollectionModel;
	use app\model\store\GoodRecommend as GoodRecommendModel;
	use app\model\store\GoodSku as GoodSkuModel;
	use app\model\store\Template as TemplateModel;
	use app\event\ucenter\Notice as NoticeEvent;
	use app\model\ucenter\User as UserModel;
	use app\event\ucenter\User as UserEvent;
	use app\model\store\Good as GoodModel;
	use think\facade\Db;
	use think\Exception;
	use app\model\store\Store as StoreModel;
	use app\model\store\GoodVisit as GoodVisitModel;
	use app\event\store\Cart as CartEvent;
	use think\facade\Config;
	use think\facade\Env;
	use yicmf\builder\Edit;

	class Good extends Base
	{

		/**
		 * @var array
		 */
		protected $param;
		/**
		 * @var array
		 */
		protected $log;

		/**
		 * 卖家信息
		 * @var StoreModel
		 */
		private $store;
		/**
		 * 会员信息
		 * @var UserModel
		 */
		private $user;
		/**
		 * 管理员信息
		 * @var UserModel
		 */
		private $admin;
		/**
		 * 商品信息
		 * @var GoodModel
		 */
		private $good;

		/**
		 * 获取商品详情
		 * @param array $param
		 * @param UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function recommend($param, $user = null)
		{
			try {
				$map = [];
				$map[] = ['status', '=', 1];
				$map[] = ['is_deny', '=', 0];
				$map[] = ['stock', '>', 0];

//				$recommend= GoodRecommendModel::where('status',1)->append(['goods'])->where('tag',$param['tag'])->find();
				$lists = GoodModel::with('cover')
					->scope('sale')->where('cover_id','>',0)->where($map)
					->where('cover_id', '>', 0)
					->where('status', 1)->limit(20)->select();
//				$data['data'] = $recommend['goods'];
				$data['data'] = $lists;
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 生成二维码
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/8 12:32
		 */
		public static function buildForm($isEdit, $data, $discount, $category, $is_supplier = 0)
		{
			if ($isEdit) {
				if ($data['is_need_send']) {
					$is_need_send = ',stock';
				} else {
					$is_need_send = '';
				}
				if ($is_supplier) {
					$base = 'store_category_id,title,home_template,is_need_send,price,cost_price,is_discount,is_discount_html,introduce,body';
				} else {
					$base = 'store_category_id,title,home_template,is_need_send,price' . $is_need_send . ',cost_price,is_discount,is_discount_html,is_open_agent,agent_price,agent_add_price,introduce,body';

				}
				$senior = 'buy_start,buy_max,sort,sms_price,buy_range,stock_alarm,auto_status,is_coupon,seller_notice,get_card_password,view_password,contact_limit';
			} else {
				if ($is_supplier) {
					$base = 'store_category_id,title,home_template,price,cost_price,is_discount,is_discount_html,introduce,body';
				} else {
					$base = 'store_category_id,title,home_template,is_need_send,stock,seller_order,price,cost_price,is_discount,is_discount_html,is_open_agent,agent_price,agent_add_price,introduce,body';
				}
				$senior = 'buy_start,buy_max,sort,sms_price,buy_range,stock_alarm,auto_status,is_coupon,seller_notice,get_card_password,view_password,contact_limit';
			}
			$template = TemplateModel::where('status', 1)->where('is_online', 1)->column('title', 'name');
			$builder = new Edit();
			$builder->title($isEdit ? '编辑商品' : '添加商品')
				->keyHidden('supplier_good_id')
				->keyHidden('is_supplier')
				->keySelect('store_category_id', '商品分类', $category, '在【商品分类】里面添加定制分类')
				->keySelect('home_template', '页面风格', ['auto' => '跟随店铺'] + $template)
				->keyNumber('sort', '排序', '数字越大越靠前！', 1)
				->keyText('title', '商品名称')
				->keyNumber('price', '价格', '用户购买价格', 1.00)
				->keyBool('is_need_send', '人工充值', '人工充值的商品不需要上卡')
				->keyRadio('sms_price', '短信费', [0 => '卖家承担', 1 => '买家承担'], '每条短信' . Config::get('pay.sms_price') . '日元')
				->keyNumber('buy_start', '起购数量', '每次购买 最少购买多少件！', 1)
				->keyNumber('buy_max', '限购数量', '每次购买 最多购买多少件,0为不限购！', 0)
				->keyNumber('buy_range', '购买间隔', '单位分钟，默认1分钟购买一次，0则不限', 0)
				->keyNumber('stock_alarm', '库存预警', '为0表示不报警', 0)
				->keyBool('auto_status', '自动下架', '销售完毕自动下架', 1)
				->keyNumber('cost_price', '成本价', $is_supplier ? ('代理进货价，当前要求至少加价' . $data['agent_add_price'] . '日元') : '填写商品进货价用于利润统计分析', 0.10)
				->keyBool('is_open_agent', '代理销售', '授权码发给代理商户即可实现代理销售', 0)
				->keyNumber('agent_price', '代理价', '授权给其他商家的销售价格')
				->keyNumber('agent_add_price', '代理加价', '授权给其他商家的最低增加价格')
				->keyNumber('stock', '库存', '人工充值商品需要填写')
				->keyBool('is_discount', '批发优惠', '是否设置批发购买时使用批发价格！', 1)
				->keyHtml('is_discount_html', $discount, '批发价格')
				->keyBool('seller_order', '发卡顺序', '是否随机发卡', 0)
				->keyBool('is_coupon', '优惠券', '是否允许使用优惠券', 1)
				//                    ->keyBool('seller_notice', '售出通知', '开启后，成功售卡将会发送邮件通知', 0)
				->keyBool('get_card_password', '提卡密码', '开启后，购买页面会提示买家填写取卡密码', 0)
				->keyTextInline('view_password', '访问密码', '填写后客户需要输入密码方可访问')
				//                    ->keyRadio('contact_limit', '客户信息', [], '客户下单时输入信息限制')
				->keyTextArea('introduce', '商品说明', '商品说明将显示在商品购买页面', '', 50, 3)
				->keyTextArea('body', '使用说明', '使用说明将显示在订单查询结果中', '', 50, 3)
				//                    ->keyBool('is_hot', '是否推荐热销')
				->keyHidden('is_supplier', '')
				->group('基本信息', $base)
				->group('高级信息', $senior);
			$builder->setTrigger('is_open_agent', 0, '')
				->setTrigger('is_open_agent', 1, 'agent_price,agent_add_price')
				->setTrigger('is_discount', 0, '')
				->setTrigger('is_discount', 1, 'is_discount_html')
				->setTrigger('is_need_send', 0, 'seller_order')
				->setTrigger('is_need_send', 1, 'stock')
				->data($data)
				//                ->explain('发布的付费商品不可变更为免费商品，但是可以参与限时免费。')
				->buttonSubmit('', '保 存');
			return $builder->fetch();
		}

		/**
		 * 生成二维码
		 * @param $param
		 * @param $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/8 12:32
		 */
		public function code_encode($param, $user)
		{
			try {
				// 验证权限
				if (!UserEvent::isAdministrator($user) && 1 != $user['is_vip']) {
					throw new \Exception('');
				}
				$data['code'] = 0;
			} catch (\Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 删除数据
		 * @param array $param
		 * @param UserModel $user
		 * @return array
		 * @author 微尘 <yicmf@qq.com>
		 */
		public function delete($param, $user = null)
		{
			try {
				if (UserEvent::isAdministrator($user)) {
					$good = GoodModel::where('id', $param['id'])->where('status', '>', -2)->find();
				} else {
					$this->store = $this->request->store;
					$good = $this->store->goods()->where('id', $param['id'])->where('status', '>', -2)->find();
				}
				if (!$good) {
					throw new Exception('商品不存在');
				}
				$good['status'] = -2;
				$good->save();
				$data['code'] = 0;
				$data['message'] = '删除成功';
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

//		/**
//		 * 禁用数据
//		 * @param   array   $param
//		 * @param UserModel $user
//		 * @return mixed
//		 * @author 微尘 <yicmf@qq.com>
//		 * @datetime: 2020/6/30 11:35
//		 */
//		public function forbid($param, $user = null)
//		{
//			try {
//				if (!UserEvent::isAdministrator($user))
//				{
//					throw new Exception('没有权限');
//				}
//
//				// 第1步 检测禁止发布的情况
//				$data['code'] = 0;
//				$data['message'] = '禁用成功';
//				$data['data'] = $result;
//			} catch (\Exception $e) {
//				$data['code'] = 1;
//				$data['message'] = $e->getMessage();
//			}
//			return $data;
//		}
		/**
		 * 生成二维码
		 * @param $param
		 * @param $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>\
		 */
		public function manage($param, $user)
		{
			try {

				if (UserEvent::isAdministrator($user)) {
					$good = GoodModel::where('id', $param['id'])->where('status', '>', -2)->find();
				} else {
					$this->store = $this->request->store;
					$good = $this->store->goods()->where('id', $param['id'])->where('status', '>', -2)->find();
					if (0 == $good['status']) {
						throw new Exception('待审核商品暂时无法操作');
					}
				}

				switch ($param['status']) {
					case 'down_sale':
						// 下架;
						if (0 == $good['is_on_sale']) {
							throw new Exception('商品已经下架');
						}
						$good['is_on_sale'] = 0;
						if (UserEvent::isAdministrator($user)) {
//							$good['is_deny'] = 1;
						}
						break;
					case 'check':
						// 过审;
						if (!UserEvent::isAdministrator($user)) {
							throw new Exception('没有权限');
						}
						$good['status'] = 1;
						break;
					case 'up_sale':
						// 上架;
						if (1 == $good['is_on_sale']) {
							throw new Exception('商品已经上架');
						}
						// 判断是否符合上架条件
						// 1. 代理商品售价符合标准
						if (1 == $good['is_supplier']) {
							$supplierGood = $good->supplierGood;
							if (($supplierGood['agent_price'] + $supplierGood['agent_add_price']) > $good['price']) {
								throw new Exception('加价不符，请先修改价格');
							}
						}
						$good['is_on_sale'] = 1;
						if (UserEvent::isAdministrator($user)) {
							$good['status'] = 1;
						}
						break;
					case 'delete':
						// 删除;
//						if (0 == $good['status']) {
//							throw new Exception('商品已经下架');
//						}
						$good['is_on_sale'] = 0;
						$good['status'] = -1;
						break;
					default:
						;
						break;
				}
				if (!$good->save()) {
					throw new Exception('数据未更新');
				}
				$data['code'] = 0;
				$data['message'] = '操作成功';
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 更新|发布商品
		 * @param array $param
		 * @param UserModel $user
		 * @return array
		 */
		public function update($param, $user = null)
		{
//			try {
			$this->user = $user;
			$this->param = $param;
			$this->store = $this->request->store;
			// 验证权限
			$this->_updateAuth();
			$this->_updateFormatData();

			Db::startTrans();
			if (empty($param['id'])) {
				$this->_updateInsert();
				// 可以发送关注通知
				$data['message'] = '新增成功';
				$data['data'] = $this->good;
			} else {
				$this->_updateEdit();
				$data['data'] = $this->good;
				$data['message'] = '修改成功';
			}
			$this->_updateSkuSpec();
			$this->_updateLog();
			Db::commit();
			$data['code'] = 0;
//			} catch (Exception $e) {
//				// 回滚事务
//				Db::rollback();
//				$data['code'] = 1;
//				$data['message'] = $e->getMessage();
//			}
			return $data;
		}

		/**
		 * 更新|发布商品
		 * @param array $param
		 * @param UserModel $user
		 * @return array
		 */
		public function import($param)
		{
//			try {
			$this->param = $param;
			$this->store = StoreModel::where('id', $param['store_id'])->find();
			$this->user = UserModel::where('id', $this->store['user_id'])->find();
			// 验证权限
//			$this->_updateAuth();
			$this->_updateFormatData();

			Db::startTrans();
			if (empty($param['id'])) {
				$this->_updateInsert();
				// 可以发送关注通知
				$data['message'] = '新增成功';
				$data['data'] = $this->good;
			} else {
				$this->_updateEdit();
				$data['data'] = $this->good;
				$data['message'] = '修改成功';
			}
			$this->_updateSkuSpec();
			$this->_updateLog();
			Db::commit();
			$data['code'] = 0;
//			} catch (Exception $e) {
//				// 回滚事务
//				Db::rollback();
//				$data['code'] = 1;
//				$data['message'] = $e->getMessage();
//			}
			return $data;
		}

		/**
		 * 权限验证
		 * @return void
		 */
		protected function _updateAuth()
		{
			// 数量控制
		}

		/**
		 * 数据校验
		 * @return void
		 */
		protected function _updateFormatData()
		{
			if (!$this->store) {
				throw new Exception('请先开通店铺功能');
			}
			if ($this->param['has_sku']) {
				$this->param['sku_arr'] = json_decode($this->param['sku_arr'], true);
			}
//				$this->param['good_category'] = explode(',', $this->param['good_category']);
//				$this->param['good_category'] = implode(',', $this->param['good_category']);
//			$goodCate = \app\model\store\GoodCategory::where('id', $this->param['good_category'])->where('status', 1)->where('level', 3)->find();
			$goodCate = \app\model\store\GoodCategory::where('id', $this->param['good_category'])->where('status', 1)->find();
			if (!$goodCate) {
				throw new Exception('分类不存在');
			}
			if ($goodCate['level'] == 3) {
				$this->param['good_category_id_one'] = $goodCate['parent']['parent_id'];
				$this->param['good_category_id_two'] = $goodCate['parent']['id'];
				$this->param['good_category_id_three'] = $goodCate['id'];
			} elseif (2 == $goodCate['level']) {
				$this->param['good_category_id_one'] = $goodCate['parent']['id'];
				$this->param['good_category_id_two'] = $goodCate['id'];
			} else {
				$this->param['good_category_id_one'] = $goodCate['id'];
			}
			if (!empty($this->param['attribute'])) {
				$this->param['attribute_arr'] = $this->param['attribute'];
			}
			// 修改
			if (!empty($this->param['id'])) {
				if (UserEvent::isAdministrator($this->user)) {
					$good = GoodModel::where('id', $this->param['id'])->find();
					$this->store = $good['store'];
					$this->user = $good['user'];
					// 管理员角色修改
					$this->admin = $this->user;
				}
			} else {
				$this->param['user_id'] = $this->user['id'];
				$this->param['store_id'] = $this->store['id'];
			}
		}


		protected function _updateEdit()
		{
			// 修改
			if (UserEvent::isAdministrator($this->user)) {
				$this->good = GoodModel::where('id', $this->param['id'])->find();
			} else {
				$this->good = GoodModel::where('store_id', $this->store['id'])->where('id', $this->param['id'])->find();
			}
			if (!$this->good) {
				throw new Exception('商品不存在');
			}
//					$reason = '';
//					if ($good['is_open_agent']) {
//						if ($this->param['title'] != $good['title']) {
//							$reason .= '【修改了标题】';
//						}
//						if ($this->param['introduce'] != $good['introduce']) {
//							$reason .= '【修改了商品说明】';
//						}
//						if ($this->param['body'] != $good['body']) {
//							$reason .= '【修改了使用说明】';
//						}
//					}
			// 增加日志
			$this->log['action'] = 'update';
			$this->log['message'] = '更新了商品';
			$this->_updateFormatCommonData();
			if (!$this->good->save()) {
				throw new Exception('修改异常');
			}
			if ($this->param['has_sku']) {
				// 开启规格
				$edit_id = [];
				foreach ($this->param['skus'] as $key => $sku) {
					$insert = $this->_updateFormatSkuData($sku, $key);
					if (empty($this->param['sku_id'][$key])) {
						// 新增
						$this->good->skus()->insert($insert);
					} else {
						// 更新
						$edit_id[] = $this->param['sku_id'][$key];
						$this->good->skus()->where('id', $this->param['sku_id'][$key])->update($insert);
					}
				}
				$has = $this->good->skus()->where('status', 1)->column('id');
				$del_id = array_values(array_diff($has, $edit_id));
				if (count($del_id)) {
					$this->good->skus()->where('id', 'in', $del_id)->update(['status' => -2]);
				}
				$this->_updateSkuCommon();
			} else {
				$skus = $this->good->skus()->where('status', 1)->select();
				$sku['title'] = $this->good['title'];
				$sku['is_free_shipping'] = $this->good['is_free_shipping'];
				$sku['freight_template_id'] = $this->good['freight_template_id'];
				$sku['good_id'] = $this->good['id'];
				$sku['stock'] = $this->good['stock'];
				$sku['stock_alarm'] = $this->good['stock_alarm'];
				$sku['stock_location'] = $this->good['stock_location'];
				$sku['body'] = $this->good['body'];
				$sku['price'] = $this->good['price'];
				$sku['market_price'] = $this->good['market_price'];
				$sku['cost_price'] = $this->good['cost_price'];
				$sku['user_id'] = $this->good['user_id'];
				$sku['store_id'] = $this->good['store_id'];
				$sku['cover_id'] = $this->good['cover_id'];
				if (count($skus) > 1 || count($skus) == 0) {
					// 之前是多规格，删除
					$this->good->skus()->where('status', 1)->update(['status' => -2]);
					$this->good->skus()->insert($sku);
				} else {
					$this->good->skus()->where('status', 1)->update($sku);
				}
			}
			$this->_updateAttribute();
		}

		protected function _updateFormatCommonData()
		{
			$this->good['refresh_time'] = time_format();
			$this->good['title'] = $this->param['title'];
			$this->good['good_category'] = $this->param['good_category'];
			$this->good['is_free_shipping'] = $this->param['is_free_shipping'];
			$this->good['freight_template_id'] = $this->param['freight_template_id'];
			$this->good['store_category_id'] = $this->param['store_category_id'];
			$this->good['is_cold'] = $this->param['is_cold'];
			$this->good['has_sku'] = $this->param['has_sku'];
			if ($this->good['has_sku'])
			{
				$this->good['sku_arr'] = $this->param['sku_arr'];
			}
			$this->good['skus'] = !empty($this->param['skus']) ? $this->param['skus'] : [];
			$this->good['price'] = $this->param['price'];
			$this->good['cost_price'] = $this->param['cost_price'];
			$this->good['market_price'] = $this->param['market_price'];
			$this->good['weight'] = $this->param['weight'];
			$this->good['volume'] = $this->param['volume'];
			$this->good['stock'] = $this->param['stock'];
			$this->good['stock_alarm'] = $this->param['stock_alarm'];
			$this->good['serial'] = $this->param['serial'];
			$this->good['barcode'] = $this->param['barcode'];
			$this->good['cover_id'] = $this->param['cover_id'];
			$this->good['images'] = $this->param['images'];
			$this->good['keywords'] = $this->param['keywords'];
			$this->good['is_commend'] = $this->param['is_commend'];
//			$this->good['guarantees'] = $this->param['guarantees'];
			$this->good['introduce'] = $this->param['introduce'];
			$this->good['sort'] = $this->param['sort'];
			$this->good['body'] = $this->param['body'];
		}

		/**
		 * @param $sku
		 * @param $key
		 * @return array
		 */
		protected function _updateFormatSkuData($sku, $key): array
		{
			return [
				'sku_spec_format' => $sku,
				'user_id' => $this->user['id'],
				'store_id' => $this->store['id'],
				'title' => $this->good['title'] . ' ' . $this->param['sku_name'][$key],
				'sku_name' => $this->param['sku_name'][$key],
				'cover_id' => $this->param['sku_cover_id'][$key]?:$this->good['cover_id'],
				'price' => $this->param['sku_price'][$key],
				'is_cold' => $this->param['is_cold'],
				'freight_template_id' => $this->param['freight_template_id'],
//				'images' => $this->param['images'],
				'market_price' => $this->param['sku_market_price'][$key],
				'cost_price' => $this->param['sku_cost_price'][$key],
				'stock' => $this->param['sku_stock'][$key],
				'stock_alarm' => $this->param['sku_stock_alarm'][$key],
				'weight' => $this->param['sku_weight'][$key],
				'volume' => $this->param['sku_volume'][$key],
				'serial' => $this->param['sku_serial'][$key],
				'barcode' => $this->param['sku_barcode'][$key],
				'is_default' => !empty($this->param['is_default'][$key]) ? 1 : 0,
			];
		}

		protected function _updateInsert()
		{
			$this->_updateFormatCommonData();
			$this->good['store_id'] = $this->store['id'];
			$this->good['user_id'] = $this->user['id'];
			$this->good = GoodModel::create($this->good);
			if (!$this->good) {
				throw new Exception('新增异常');
			}
			// 属性
			$this->_updateAttribute();
			if ($this->param['has_sku']) {
				// 开启多规格
				$insertAll = [];
				foreach ($this->param['skus'] as $key => $sku) {
					$insertAll[] = $this->_updateFormatSkuData($sku, $key);
				}
				if (!count($insertAll)) {
					throw new Exception('数据错误');
				}
				$re = $this->good->skus()->saveAll($insertAll);
				if (!$re) {
					throw new Exception('添加规格异常');
				}
				$this->_updateSkuCommon();
			} else {
				// 关联一个
				$insert = $this->good->toArray();
				unset($insert['id']);
				$insert['is_cold'] = $this->param['is_cold'];
				$insert['freight_template_id'] = $this->param['freight_template_id'];
				$insert['is_free_shipping'] = $this->good['is_free_shipping'];
				$insert['is_default'] = 1;
				$insert['store_id'] = $this->store['id'];
				$insert['sku_spec_format'] = '{}';
				$sku = $this->good->skus()->save($insert);
				if (!$sku) {
					throw new Exception('新增异常');
				}
				$this->good['sn'] = $sku['sn'];
				$this->good->save();
			}

			// 增加日志
			$this->log['action'] = 'add';
			$this->log['message'] = '新增了商品';
			$this->log['title'] = $this->param['title'];
			$this->log['body'] = $this->param['body'];
		}

		protected function _updateLog()
		{
			if ($this->admin) {
				$this->log['user_id'] = $this->admin['id'];
			} else {
				$this->log['user_id'] = $this->user['id'];
			}
			$this->log['title'] = $this->good['title'];
			$this->log['body'] = $this->good['body'];
			$this->log['data'] = $this->param;
			$this->good->logs()->save($this->log);
		}

		/**
		 * 关联属性
		 * @throws Exception
		 */
		protected function _updateAttribute()
		{
			// 属性，先清空
			GoodAttributeValueModel::where('good_id', $this->good['id'])->delete();
			if (empty($this->param['attribute'])) {
				return;
			}
			$attribute = $this->param['attribute'];
			$goodAttributes = GoodAttributeModel::where('id', 'in', array_keys($attribute))->select();
			$insertAll = [];
			foreach ($goodAttributes as $goodAttribute) {
				if ($goodAttribute['type'] == 0) {
					//单选
					$value = $goodAttribute['value_format'][$attribute[$goodAttribute['id']]];
					$value_format = $attribute[$goodAttribute['id']];
				} elseif (1 == $goodAttribute['type']) {
					// 多选
					$temp = [];
					foreach ($attribute[$goodAttribute['id']] as $item) {
						$temp[] = $goodAttribute['value_format'][$item];
					}
					$value = implode(',', $temp);
					$value_format = implode(',', $attribute[$goodAttribute['id']]);
				} else {
					// 自定义
					$value = $attribute[$goodAttribute['id']];
					$value_format = $attribute[$goodAttribute['id']];
				}
				$insertAll[] = [
					'good_id' => $this->good['id'],
					'good_attribute_id' => $goodAttribute['id'],
					'name' => $goodAttribute['name'],
					'value' => $value,
					'value_format' => $value_format,
				];
			}
			$this->good->attributes()->saveAll($insertAll);
		}

		/**
		 * 根据sku更新公共数据
		 */
		protected function _updateSkuCommon()
		{
			// 更新主数据
			$default = $this->good->skus()->where('is_default', 1)->where('status', 1)->find();
			if (!$default) {
				// 默认价格最低的
				$default = $this->good->skus()->where('status', 1)->order('price ASC')->find();
				$default['is_default'] = 1;
				$default->save();
			}
			$this->good['sn'] = $default['sn'];
			$this->good['price'] = $default['price'];
			$this->good['market_price'] = $default['market_price'];
			$this->good['cost_price'] = $default['cost_price'];
			$this->good['weight'] = $default['weight'];
			$this->good['volume'] = $default['volume'];
			$this->good['serial'] = $default['serial'];
			$this->good['barcode'] = $default['barcode'];
			$this->good['stock'] = $this->good->skus()->sum('stock');
			$this->good['stock_alarm'] = $this->good->skus()->min('stock_alarm');
			$this->good->save();
		}

		/**
		 * @return void
		 */
		protected function _updateSkuSpec()
		{
			// sku 更新
			if ($this->good['has_sku']) {
				if(is_array($this->good['sku_arr']))
				{
					foreach ($this->good['sku_arr'] as $item) {
						if (!$this->store->skus()->where('name', $item['name'])->where('status', 1)->find()) {
							$this->store->skus()->save(['name' => $item['name']]);
						}
					}
				}
			}
			return;
		}

		/**
		 * @param GoodModel $good
		 * @param string $reason
		 * @throws Exception
		 */
		protected function _downSaleAgent($good, $reason)
		{
			// 全部下架，代理处理
			// 开放代理，同步库存
			if ($good->agentGoods()->find()) {
				$agentGoods = $good->agentGoods()->where('is_on_sale', 1)->select();
				foreach ($agentGoods as $index => $agentGood) {
					// 发送通知
					$param = [];
					$param['good_id'] = $agentGood['id'];
					$param['type'] = 'down_sale_agent';
					$param['reason'] = $reason;
					NoticeEvent::send($param, $agentGood->store->user);
				}
				$good->agentGoods()->where('status', '>', -2)->update(['is_on_sale' => 0, 'cost_price' => $good['agent_price']]);
			}

		}

		/**
		 * 获取商品详情
		 * @param      $param
		 * @param null|UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function detail($param, $user = null)
		{
			try {

				$sku = GoodSkuModel::with(['cover'])->where('status', 1)
					->where('sn|id', $param['id'])
					->find();
				$good = GoodModel::with(['store' => ['avatar'], 'cover', 'discounts', 'skus'])->where('status', 1)
					->where('is_deny', 0)
					->where('is_on_sale', 1)
					->where('id', $sku['good_id'])
					->find();
				if (!$good) {
					throw new Exception('商品不存在或者已经下架');
				}
				// 热门评论

//				$good['hot_evaluates'] = $good->evaluates()->with('user')
				$data['data']['hot_evaluates'] = GoodEvaluateModel::with(['user' => ['avatar']])
					->where('good_id', $good['id'])
					->where('status', 1)
//					->append(['images'])
					->order('create_time DESC')
					->limit(3)->select();

				$data['data']['good'] = $good;
				$data['data']['sku'] = $sku;
				if ($user) {
					$data['data']['is_collection'] = $user->collections()->where('sku_id', $sku['id'])->where('status', 1)->find() ? 1 : 0;;
				}
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 搜索
		 * @param      $param
		 * @param null|UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function search($param, $user = null)
		{
			try {
				$order = isset($param['order']) ? $param['order'] : 'recommend';
				if ($order == 'price') {
					$sort = 'price ASC';
				} elseif ($order == 'evaluation') {
					$sort = 'evaluation DESC';
				} elseif ($order == 'sale') {
					$sort = 'evaluation DESC';
				} else {
					$sort = 'update_time DESC';
				}
				if (!empty($param['category_id'])) {
					$cateids = GoodCategory::getChildWithIds($param['category_id']);
					$lists = GoodModel::with(['cover', 'skus'])->scope('sale')->where('cover_id','>',0)->order($sort)->where('good_category', 'in', $cateids)
						->paginate([
							'query'=>[
								'category_id'=>$param['category_id']
							]
						]);
				} elseif (!empty($param['keywords'])) {
					$lists = GoodModel::with(['cover', 'skus'])->where('status', 1)->scope('sale')
						->where('is_deny', 0)
						->where('is_on_sale', 1)->where('cover_id','>',0)
						->where('title|body|keywords|ad', 'like', '%' . $param['keywords'] . '%')
						->order($sort)
						->paginate();
				}  elseif (!empty($param['barcode'])) {
					$lists = GoodModel::with(['cover', 'skus'])->where('status', 1)->scope('sale')
						->where('is_deny', 0)
						->where('is_on_sale', 1)->where('cover_id','>',0)
						->where('barcode', $param['barcode'])
						->order($sort)
						->paginate();
				} else {
					$lists = GoodModel::with(['cover', 'skus'])->scope('sale')->where('cover_id','>',0)->order($sort)
						->paginate();
				}


				$data['data'] = $lists;
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 根据活动获取商品列表
		 * @param ActivityModel $activity
		 * @param null|UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function activity($activity, $user = null)
		{
			try {
				$order = isset($param['order']) ? $param['order'] : 'recommend';
				if ($order == 'price') {
					$sort = 'price ASC';
				} elseif ($order == 'evaluation') {
					$sort = 'evaluation DESC';
				} elseif ($order == 'sale') {
					$sort = 'evaluation DESC';
				} else {
					$sort = 'update_time DESC';
				}
				if (isset($param['keywords'])) {
					$lists = GoodModel::with(['cover', 'skus'])->where('status', 1)
						->where('is_deny', 0)
						->where('is_on_sale', 1)
						->where('cover_id', '>',1)
						->where('activity_id', $activity['id'])
						->where('title|body', 'like', '%' . $param['keywords'] . '%')
						->order($sort)
						->paginate([
							'query'=>[
								'id'=>$activity['id']
							]
						]);
				} else {
					$lists = GoodModel::with(['cover', 'skus'])->scope('sale')->order($sort)
						->where('is_on_sale', 1)
						->where('cover_id', '>',1)
						->where('activity_id', $activity['id'])
						->paginate([
							'query'=>[
								'id'=>$activity['id']
							]
						]);
				}


				$data['data'] = $lists;
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 根据sku参数 搜索sku
		 * @param      $param
		 * @param null|UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function sku($param, $user = null)
		{
			try {

				$sku = GoodSkuModel::where('status', 1)
					->where('sn|id', $param['sku_id'])
					->find();
				if (!$sku) {
					throw new Exception('商品不存在');
				}

				$skus = GoodSkuModel::where('status', 1)
					->where('good_id', $sku['good_id'])
					->select();
				foreach ($skus as $item) {
					$sku_spec_format = json_decode($item['sku_spec_format'], true);
					$flat = true;
					if (!is_array($param['sku'])) {
						$param['sku'] = json_decode($param['sku'], true);
					}
					foreach ($param['sku'] as $name => $value) {
						if (!isset($sku_spec_format[$name]) || $sku_spec_format[$name] != $value) {
							$flat = false;
							break;
						}
					}
					if ($flat) {
						$new_sku = $item;
						break;
					}
				}
				if (!isset($new_sku)) {
					throw new Exception('系统异常');
				}
				$good = GoodModel::with(['cover'])->where('status', 1)
					->where('is_deny', 0)
					->where('is_on_sale', 1)
					->where('id', $sku['good_id'])
					->find();
				$data['data']['sku'] = $new_sku;
				$data['data']['good'] = $good;
				$data['data']['url'] = (string)url('Good/detail', ['id' => $new_sku['sn']]);
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
				$data['line'] = $e->getLine();
			}
			return $data;
		}

		/**
		 * 推荐
		 * @param      $param
		 * @param null|UserModel $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 */
		public function recommends($param, $user = null,$limit = 10)
		{
			try {
				$lists = GoodModel::with(['cover', 'skus'])->where('status', 1)
					->where('is_deny', 0)
					->where('is_on_sale', 1)
					->orderRand()
					->limit($limit)->where('cover_id','>',0)
//					->where('title|body','like', '%'.$param['keywords'].'%')
					->select();

				$data['data'] = $lists;
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

		/**
		 * 访问商品
		 * @param           $param
		 * @param StoreModel $store
		 * @return mixed
		 */
		public static function visit($param, $user = null, $from = 1)
		{
			try {

				$sku = GoodSkuModel::where('id|sn', $param['sku_id'])->where('status', 1)->find();
				if (!$sku) {
					throw new Exception('商品不存在');
				}

				if ($user) {
					// 已经登录
					$visit = GoodVisitModel::where('sku_id', $sku['id'])->where('from', $from)->where('is_use', 1)->where('user_id', $user['id'])->where('status', 1)->find();
				} else {
					$visit = GoodVisitModel::where('sku_id', $sku['id'])->where('from', $from)->where('user_id', null)->where('ip', request()->ip())->where('status', 1)->find();
				}

				if ($visit) {
					$visit['date_time'] = time_format('Y-m-d');
					$visit['times'] = $visit['times'] + 1;
					$visit->save();
				} else {
					$visit['times'] = 1;
					$visit['sku_id'] = $sku['id'];
					$visit['from'] = $from;
					$visit['store_id'] = $sku['store_id'];
					$visit['good_id'] = $sku['good_id'];
					$visit['date_time'] = time_format('Y-m-d');
					if ($user) {
						$visit['user_id'] = $user['id'];
					}
					$visit = GoodVisitModel::create($visit);
				}
				GoodModel::where('id', $visit['good_id'])->inc('visit')->update();
				GoodSkuModel::where('id', $visit['sku_id'])->inc('visit')->update();
				Db::commit();
				$data['code'] = 0;
				$data['message'] = 'ok';
			} catch (Exception $e) {
				Db::rollback();
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}


		/**
		 * 删除足迹
		 * @param $param
		 * @param $user
		 * @return array
		 */
		public static function deleteFoot($param, $user)
		{
			try {
				$visit = GoodVisitModel::where('user_id', $user['id'])->where('id', $param['id'])->where('is_use', 1)->where('status', 1)->find();
				if (!$visit) {
					throw new Exception('收藏不存在');
				}
				$visit['is_use'] = 0;
				$visit->save();
				$data['code'] = 0;
				$data['message'] = '删除成功';
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}


		/**
		 * 评价列表
		 * @param $param
		 * @param $user
		 * @return mixed
		 * @author  : 微尘 <yicmf@qq.com>
		 * @datetime: 2019/5/8 12:32
		 */
		public function evaluates($param, $user)
		{
			try {
				// 验证权限
				$good = GoodModel::where('id', $param['id'])->where('id', $param['id'])->find();
				if ($good['status'] != 1) {
					throw new Exception('当前商品异常');
				}
				$data['code'] = 0;
				$data['data'] = GoodEvaluateModel::with(['user' => ['avatar']])
					->where('good_id', $good['id'])
					->where('status', 1)
					->append(['images'])
					->order('create_time DESC')->limit(3)->paginate(50);
				$all = $good->evaluates()->where('status', 1)->count();
				$best = $good->evaluates()->where('status', 1)->where('desc_star', 5)->count();
				$middle = $good->evaluates()->where('status', 1)->where('desc_star', 'in', '2,3,5')->count();
				$bad = $good->evaluates()->where('status', 1)->where('desc_star', 1)->count();
				$data['good'] = $good;
				$data['tabs'] = [
					'全部' . $all,
					'好评' . $best,
					'中评' . $middle,
					'差评' . $bad,
				];
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}


		/**
		 * 添加收藏
		 * @param $param
		 * @param $user
		 * @return array
		 */
		public static function collection($param, $user)
		{
			try {

				if (!$user) {
					throw new Exception('请先登录');
				}
				if (isset($param['method']) && 'cancel' == $param['method']) {
					// 取消收藏
					$sku = GoodSkuModel::where('id|sn', $param['id'])->find();
					if (!$sku) {
						throw new Exception('商品不存在');
					}
					$visit = GoodCollectionModel::where('user_id', $user['id'])->where('sku_id', $sku['id'])->where('status', 1)->find();
					if (!$visit) {
						throw new Exception('收藏不存在');
					}
					$visit['status'] = -2;
					$visit->save();
					// 取消收藏
//					if ($user->collections()->where('sku_id',$sku['id'])->where('status',1)->find())
//					{
//						$user->collections()->where('sku_id',$sku['id'])->where('status',1)->update(['status'=>-2]);
//					}
					$data['message'] = '取消收藏成功';
					$data['data']['is_collection'] = $user->collections()->where('sku_id', $sku['id'])->where('status', 1)->find() ? 1 : 0;
				} elseif (isset($param['method']) && 'cart' == $param['method']) {
					// 加入购物车
					$visit = GoodCollectionModel::where('user_id', $user['id'])->where('id', $param['id'])->where('status', 1)->find();
					if (!$visit) {
						throw new Exception('收藏不存在');
					}
					$visit['status'] = -2;
					$visit->save();
					$cart = new CartEvent();
					$re = $cart->add(['sku_id' => $visit['good_sku']['sn'], 'number' => 1], $user);
					if ($re['code'] != 0)
					{
						throw new Exception($re['message']);
					}
					$data['message'] = '加入购物车成功';
				} else {
					$sku = GoodSkuModel::where('id|sn', $param['id'])->find();
					if (!$sku) {
						throw new Exception('商品不存在');
					}
					// 添加收藏
					if (!$user->collections()->where('sku_id', $sku['id'])->where('status', 1)->find()) {

						// 新增
						$insert = [];
						$insert['sku_id'] = $sku['id'];
						$insert['good_id'] = $sku['good_id'];
						$insert['store_id'] = $sku['store_id'];
						$insert['from'] = 'web';
						$user->collections()->save($insert);
					}
					$data['message'] = '收藏成功';
					$data['data']['is_collection'] = $user->collections()->where('sku_id', $sku['id'])->where('status', 1)->find() ? 1 : 0;
				}
				$data['code'] = 0;
			} catch (Exception $e) {
				$data['code'] = 1;
				$data['message'] = $e->getMessage();
			}
			return $data;
		}

	}
